// pages/launch/launch.js
const templateAPI = require('../../api/template.js');
const QQMapWX = require('../../libs/qqsdk/qqmap-wx-jssdk.js');
const util = require('../../utils/util.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    template: {
      name: ''
    },
    form: null,
    variableList: [],
    map: {
      hidden: true,
      markers: [{
        iconPath: "/resources/wxb_search2.png",
        id: 0,
        width: 50,
        height: 50
      }],
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.qqmapsdk = new QQMapWX({
      key: 'KULBZ-DGV6F-CNVJJ-NE44T-5QSZT-Y4FP5'
    });
    const template = JSON.parse(options.template);
    const template = {
      "id": 9006928671805747,
      "name": "(Sprint 27)IC Custom Support",
      "templateStatus": "Live",
      "phaseTemplates": [{
        "templateId": 0,
        "name": "New | Updated | Closed",
        "messageFlag": 1,
        "contactsFlag": 3,
        "settingsFlag": 1,
        "phaseDefinitions": [{
          "id": 1001,
          "status": "A",
          "isDefault": false,
          "name": "New",
          "seq": 0
        }, {
          "id": 1002,
          "status": "A",
          "isDefault": false,
          "name": "Updated",
          "seq": 0
        }, {
          "id": 1003,
          "status": "A",
          "isDefault": false,
          "name": "Closed",
          "seq": 0
        }],
        "formTemplate": {
          "subject": "IC Custom Support {Building}",
          "preMessage": "{Message}",
          "formVariableItems": [{
            "val": ["{time}"],
            "variableName": "Current Time",
            "isRequired": false,
            "seq": 1,
            "variableId": 10003
          }, {
            "variableName": "Message",
            "isRequired": false,
            "seq": 2,
            "variableId": 444206992637455
          }, {
            "val": ["Pasadena City Hall"],
            "variableName": "Building",
            "isRequired": false,
            "seq": 3,
            "variableId": 444206992639756
          }, {
            "val": ["IC Dev Team"],
            "variableName": "New IC Groups",
            "isRequired": false,
            "seq": 4,
            "variableId": 9007066110757208
          }]
        },
        "broadcastTemplate": {
          "accountId": 0,
          "broadcastContacts": {
            "groupIds": [884011643710756],
            "contactSearchType": "AllOr",
            "sequenceGroupEnabled": true,
            "answerNeeded": "ABC",
            "defaultSeqGroupQuota": 1,
            "sequenceGroupInterval": 5,
            "sequenceShifts": [{
              "shiftId": 884011643704339,
              "confirmationQuota": 1
            }]
          },
          "resourceBundleId": 0,
          "organizationId": 0,
          "publicMessages": {},
          "type": "Polling",
          "id": 0,
          "message": {
            "accountId": 0,
            "organizationId": 0,
            "contentType": "Text",
            "id": 0,
            "title": "IC Custom Support {Building}",
            "conferenceBridgeId": 0,
            "resourceBundleId": 0,
            "questionaire": {
              "inputOptionAllowable": false,
              "multipleSelected": false,
              "answers": [{
                "quotaNum": 0,
                "name": "ABC"
              }, {
                "quotaNum": 0,
                "name": "BCD"
              }],
              "required": false
            },
            "lastModifiedId": 0,
            "createdId": 0,
            "rtfContent": "<meta id=\"meta\" name=\"viewport\" content=\"width=device-width; initial-scale=1.0\">Some <span style=\"color: rgb(204, 0, 0);\">RTF </span>conte<span style=\"font-style: italic; font-weight: bold;\">nt&nbsp;{Message}</span><div><b><i><br></i></b></div><div><b><i><br></i></b></div><div><b><i><br></i></b></div><div><b><i><br></i></b></div><div><b><i><br></i></b><div><table border=\"1\" cellpadding=\"2\" cellspacing=\"2\"><tbody><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;A</td><td>&nbsp;</td><td>&nbsp;</td><td>C&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></tbody></table><img alt=\"Image did not load.\" src=\"https://s3.amazonaws.com/qadev.prerelease.img.email/RTFImage_59810e3d5c2cbe4c15c48799.png\"></div></div>"
          },
          "broadcastSettings": {
            "throttlDefaultAmount": 0,
            "throttle": false,
            "mobileSettings": {
              "requestComment": false,
              "requestImage": false,
              "requestLocation": false,
              "allowShare": false,
              "requireConfirm": false,
              "pushAlertEnabled": false
            },
            "deliverPaths": [{
              "accountId": 0,
              "pathId": 241901148045316,
              "organizationId": 0,
              "awarePathId": 0,
              "id": 888409690213043,
              "expose": false,
              "isDefault": false,
              "mandatory": false,
              "resourceBundleId": 0,
              "editable": false,
              "seq": 0,
              "lastModifiedId": 0,
              "createdId": 0,
              "extRequired": false,
              "displayFlag": false,
              "default": false
            }, {
              "accountId": 0,
              "pathId": 219910915489808,
              "organizationId": 0,
              "awarePathId": 0,
              "id": 888409690213056,
              "expose": false,
              "isDefault": false,
              "mandatory": false,
              "resourceBundleId": 0,
              "editable": false,
              "seq": 0,
              "lastModifiedId": 0,
              "createdId": 0,
              "extRequired": false,
              "displayFlag": false,
              "default": false
            }, {
              "accountId": 0,
              "pathId": 241901148045319,
              "organizationId": 0,
              "awarePathId": 0,
              "id": 888409690213057,
              "expose": false,
              "isDefault": false,
              "mandatory": false,
              "resourceBundleId": 0,
              "editable": false,
              "seq": 0,
              "lastModifiedId": 0,
              "createdId": 0,
              "extRequired": false,
              "displayFlag": false,
              "default": false
            }, {
              "accountId": 0,
              "pathId": 241901148045324,
              "organizationId": 0,
              "awarePathId": 0,
              "id": 888409690213065,
              "expose": false,
              "isDefault": false,
              "mandatory": false,
              "resourceBundleId": 0,
              "editable": false,
              "seq": 0,
              "lastModifiedId": 0,
              "createdId": 0,
              "extRequired": false,
              "displayFlag": false,
              "default": false
            }, {
              "accountId": 0,
              "pathId": 241901148045315,
              "organizationId": 0,
              "awarePathId": 0,
              "id": 888409690213066,
              "expose": false,
              "isDefault": false,
              "mandatory": false,
              "resourceBundleId": 0,
              "editable": false,
              "seq": 0,
              "lastModifiedId": 0,
              "createdId": 0,
              "extRequired": false,
              "displayFlag": false,
              "default": false
            }],
            "requirePinForMessage": false,
            "deliveryMethodInterval": 0,
            "bookConference": false,
            "cycleInterval": 0,
            "duration": 1,
            "senderCallerInfos": [{
              "countryName": "United States",
              "accountId": 0,
              "countryCode": "US",
              "resourceBundleId": 0,
              "organizationId": 0,
              "id": 0,
              "callerId": "2012345678",
              "isDefault": true,
              "createdId": 0,
              "lastModifiedId": 0
            }],
            "contactCycles": 1,
            "language": "en_US",
            "recipientApp": false,
            "senderEmail": "PangolinTeamDemo1@everbridge.net",
            "confirm": true,
            "smsCallBack": false,
            "deliveryPathOrder": "Contact"
          },
          "priority": "NonPriority",
          "lastModifiedId": 0,
          "createdId": 0,
          "useEscalation": false
        },
        "ignoreVariable": false,
        "evaluateAll": false
      }],
      "accountId": 448605039100272,
      "status": "A",
      "createdId": 444206992591625,
      "createdName": "Albert Luo",
      "lastModifiedId": 884011643701506,
      "lastModifiedName": "Albert Luo Multiple",
      "createdDate": 1510138483048,
      "lastModifiedDate": 1511492872963,
      "organizationId": 888409690211392,
      "resourceBundleId": 888409690211649
    };

    that.setData({
      'form': template.phaseTemplates[0].formTemplate
    })
    that.setData({
      'variableList': [{
        "id": 444206992637455,
        "name": "Message",
        "seq": 0,
        "varType": "Textarea",
        "accountId": 448605039100272,
        "status": "A",
        "createdId": 448605039100303,
        "createdName": "SmartConference1 wzhang",
        "lastModifiedId": 448605039100303,
        "lastModifiedName": "SmartConference1 wzhang",
        "createdDate": 1493105838922,
        "lastModifiedDate": 1493107322955,
        "organizationId": 888409690211392,
        "resourceBundleId": 888409690211649,
        "extProperties": {
          "rows": "10",
          "cols": "200"
        }
      }, {
        "id": 444206992639756,
        "name": "Building",
        "seq": 0,
        "varType": "Single",
        "variableOptions": [{
          "txt": "Pasadena City Hall",
          "val": "Pasadena City Hall",
          "seq": 0,
          "isSelected": true
        }, {
          "txt": "Pasadena Convention Center",
          "val": "Pasadena Convention Center",
          "seq": 0,
          "isSelected": false
        }, {
          "txt": "The Westin Pasadena",
          "val": "The Westin Pasadena",
          "seq": 0,
          "isSelected": false
        }],
        "accountId": 448605039100272,
        "status": "A",
        "createdId": 444206992592324,
        "createdName": "Incident Admin&Operator",
        "lastModifiedId": 444206992591625,
        "lastModifiedName": "Albert Luo",
        "createdDate": 1499270661022,
        "lastModifiedDate": 1499273096940,
        "organizationId": 888409690211392,
        "resourceBundleId": 444206992590732
      }, {
        "id": 9007066110757208,
        "name": "New IC Groups",
        "seq": 0,
        "varType": "ComboBox",
        "accountId": 448605039100272,
        "status": "A",
        "createdId": 444206992591625,
        "createdName": "Albert Luo",
        "lastModifiedId": 444206992591625,
        "lastModifiedName": "Albert Luo",
        "createdDate": 1510154828031,
        "lastModifiedDate": 1510154828031,
        "organizationId": 888409690211392,
        "resourceBundleId": 888409690211649,
        "extProperties": {
          "datasource": "Groups"
        }
      }]
    });
    that.updateForm();
    return;
    this.setData({
      template: template
    });
    wx.showLoading({
      title: 'Loading...',
    });
    const doneCallBack = () => {
      wx.hideLoading();
    }
    templateAPI.getTemplate(template.id, res => {
      const remoteTemplate = res.data.result;
      that.setData({
        'template': remoteTemplate,
      })
      that.setData({
        'form': remoteTemplate.phaseTemplates[0].formTemplate
      });
      that.updateForm(doneCallBack.bind(that));
    })
    templateAPI.getVariables(template.id, res => {
      that.setData({
        'variableList': res.data.page.data || []
      });
      that.updateForm(doneCallBack.bind(that));
    }, 'New')

  },
  updateForm: function (doneCallBack) {
    if (this.data.variableList.length > 0 && this.data.form) {
      //compose together
      const formList = this.data.form.formVariableItems;
      let combinedVariableList = this.data.variableList.map(item => {
        let combinedVariable = item;
        const formVarFound = formList.find(formVar => { return formVar.variableId === item.id });
        if (formVarFound) {
          combinedVariable.val = formVarFound.val;
          combinedVariable.isRequired = formVarFound.isRequired;
          return combinedVariable;
        }
      });
      this.setData({
        'variableList': combinedVariableList
      })
    }
    if (typeof doneCallBack === 'function') {
      doneCallBack();
    }
  },
  locationLinkClick: function (options) {
    const variableId = options.target.dataset.id;
    const coordinate = this.getFormData(variableId);
    const that = this;
    that.currentVariableId = variableId;
    let currentCoordinate = {};
    if (coordinate) {
      currentCoordinate = {
        latitude: coordinate.split(',')[0],
        longitude: coordinate.split(',')[1],
      }
      that.updateMapData(currentCoordinate);
    } else {
      that.currentLocationClick();
    }
  },
  mapPickerRegionChange: function (options) {
    var that = this;
    if (that.data.map.hidden === true || options.type === 'begin') {
      return;
    }
    this.mapCtx.getCenterLocation({
      success: function (res) {
        that.updateMapData(res)
      }
    })
  },
  currentLocationClick: function () {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.updateMapData({
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  updateMapData: function (data) {
    const that = this;
    let address = '';
    that.qqmapsdk.reverseGeocoder({
      location: data,
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        address = res.result && res.result.address;
        that.setData({
          map: {
            hidden: false,
            latitude: data.latitude,
            longitude: data.longitude,
            address: address,
            markers: [{
              iconPath: "/resources/wxb_location.png",
              latitude: data.latitude,
              longitude: data.longitude,
              id: 0,
              width: 40,
              height: 40,
              callout: {
                padding: 5,
                borderRadius: 3,
                content: `Lat: ${data.latitude}, Lon: ${data.longitude}\nAddress: ${address}`,
                display: 'ALWAYS'
              }
            }],
          }
        })
      }
    });

  },
  useLocationClick: function (options) {
    const variableId = this.currentVariableId;
    const mapData = this.data.map
    const selectedVal = `${mapData.latitude},${mapData.longitude}`;
    this.updateVariableListData(variableId, selectedVal);
    this.updateVariableListData(variableId, mapData.address, 1);
    this.setData({
      map: {
        hidden: true
      }
    })
  },
  datePickerChanged: function (event) {
    const variableId = event.target.dataset.id;
    const selectedDate = new Date(event.detail.value);

    this.updateVariableListData(variableId, util.formatDate(selectedDate));
  },
  pickerChanged: function(event) {
    const variableId = event.target.dataset.id;
    const selectedIndex = event.detail.value;
    const selectedVal = this.getFormItem(variableId)['variableOptions'][selectedIndex];

    this.updateVariableListData(variableId, selectedVal.txt);
  },
  getFormItem: function(variableId){
    let formData = this.data.variableList;
    let foundVariable = formData.find(item => { return item.id === variableId });
    return foundVariable;
  },
  getFormData: function (variableId, index = 0) {
    let foundVariable = this.getFormItem(variableId);
    return foundVariable && foundVariable.val[index];
  },
  updateVariableListData: function (variableId, newValue, index = 0) {
    let formData = this.data.variableList;
    let foundVariable = formData.find(item => { return item.id === variableId });
    if (foundVariable) {
      foundVariable.val[index] = newValue;
    }
    this.setData({
      'variableList': formData
    })
  },
  updateFormData: function () {
    let variableList = this.data.variableList;
    let formData = this.data.form.formVariableItems;
    variableList.forEach(item => {
      let foundFormData = formData.find(formitem => {
        return formitem.variableId === item.id;
      });
      if (foundFormData) {
        foundFormData.val = item.val;
      }
    })
  },
  updateAllVariableListData: function (postValue) {
    for (let key in Object.keys(postValue)) {
      if (key.indexOf('form.') === 0) {
        const keyArray = key.split('.');
        let index = 0;
        if (keyArray.length > 2) {
          index = 1;
        }
        if (postValue[key] !== this.getFormData(keyArray[1], index)) {
          this.updateVariableListData(keyArray[1], postValue[key], index)
        }
      }
    }
  },
  previewOrLaunchIncident: function (options) {
    const postValue = options.detail.value;
    this.updateAllVariableListData(postValue);
    this.updateFormData();
    const templateData = this.data.template;
    const formData = this.data.form;
    let toPostParams = {
      name: templateData.name,
      incidentAction: 'Launch',
      incidentPhases: [
        {
          phaseTemplate: {
            templateId: templateData.id,
            broadcastTemplate: {
              message: {
                title: postValue.subject
              }
            },
            formTemplate: formData
          }
        }
      ]
    };
    console.log(toPostParams);
    templateAPI.launch(toPostParams, res => {
      let incidentId = res.data.id;
      if (incidentId) {
        //TODO reLaunch to History tab & Goto detail page;
        wx.navigateTo({
          url: '../detail/detail?incident='+JSON.stringify({
            id: incidentId
          }),
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setNavigationBarTitle({
      title: 'Launch Incident'
    });
    this.mapCtx = wx.createMapContext('mapPicker', this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})